

define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template', 'fastflow-form-builder', 'fastflow-base'], function ($, undefined, Backend, Table, Form, Template, FormBuilder, FastflowBase) {

    var Controller = {
        baseForm: ['name', 'title'],
        extraForm: {
            inputText: ['defaultValue'],
            inputNumber: ['decimal', 'defaultValue'],
            radio: ['options', 'defaultValue'],
            checkbox: ['options', 'defaultValue'],
            selectpicker: ['options', 'multiple', 'defaultValue'],
            selectpage: ['datasource', 'multiple', 'defaultValue'],
            userSelectpage: ['multiple', 'defaultValue'],
            adminSelectpage: ['multiple', 'defaultValue'],
            categorySelectpage: ['multiple', 'defaultValue'],
            image: ['multiple', 'defaultValue'],
            file: ['multiple', 'defaultValue'],
            tagsinput: ['defaultValue'],
            switch: ['defaultValue'],
        },
        hideRestBtn: ['userSelectpage', 'adminSelectpage', 'categorySelectpage'],
        suffixNameForm: ['selectpage', 'file', 'image', 'tagsinput', 'datetimeRange', 'switch', 'radio', 'checkbox'],
        suffix: {
            selectpage: {1: '_id', 2: '_ids'},
            file: {1: 'file', 2: 'files'},
            image: {1: 'image', 2: 'images'},
            tagsinput: {1: 'tag'},
            datetimeRange: {1: 'range'},
            switch: {1: 'switch'},
            radio: {1: 'data'},
            checkbox: {1: 'data'}
        },
        index: function () {
            Table.api.init({
                extend: {
                    index_url: 'fastflow/flow/bill/index' + location.search,
                    add_url: 'fastflow/flow/bill/add',
                    edit_url: 'fastflow/flow/bill/edit',
                    del_url: 'fastflow/flow/bill/del',
                    multi_url: 'fastflow/flow/bill/multi',
                    import_url: 'fastflow/flow/bill/import',
                    table: 'fastflow_bill',
                }
            });

            var table = $("#table");

            table.on('load-success.bs.table', function (e, data) {
                FastflowBase.api.renderbadge();
            });

            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {field: 'id', title: __('Id')},
                        {field: 'bill_name', title: __('Bill_name'), operate: 'LIKE'},
                        {field: 'bill_table', title: __('Bill_table'), operate: 'LIKE'},
                        {field: 'controller', title: __('Controller'), operate: 'LIKE'},
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: '',
                            title: __('BillAuth'),
                            operate: false,
                            formatter: Controller.api.formatter.billauth
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Controller.api.events.operate,
                            formatter: Controller.api.formatter.operate
                        }
                    ]
                ]
            });

            Table.api.bindevent(table);
        },

        fromtable: function () {
            Controller.fromApi.bindevents();
            $("select[name='table']").trigger("change");
            Controller.api.bindevent();
        },
        add: function () {
            $('input[name="billName"]').val('单据（' + FormBuilder.getRandId(4) + ')');
            var billTable = Config.prefix + FormBuilder.getRandName(6);
            $('input[name="billTable"]').val(billTable);
            var controller = Controller.addApi.buildControlerStr(billTable);
            $('input[name=controller]').val(controller);
            //适配移动端
            window.onload=function(){
                $('.loading').remove();
            };
            $(document).ready(function () {
                $('.loading').remove();
            });
            FormBuilder.create('widget', 'customform');
            Controller.addApi.bindevents();
            Form.api.bindevent($('form[role=form]'));
        },
        edit: function () {
            Controller.api.bindevent();
        },
        auth: function () {
            Controller.api.bindevent();
        },
        addApi: {
            bindevents: function () {
                Controller.addEvents.clearClick();
                Controller.addEvents.widgetRemove();
                Controller.addEvents.widgetClick();
                Controller.addEvents.sortableUpdate();
                Controller.addEvents.inputChange();
                Controller.addEvents.createBill();
                Controller.addEvents.selectIcon();
                Controller.addEvents.billConfigTabClick();
                Controller.addEvents.tableRelationChange();
                Controller.addEvents.collapseClick();
            },
            initForm: function (data) {
                Controller.addApi.visibleForm(data);
                Controller.addApi.fillForm(data);
            },
            visibleForm: function (data) {
                $('#widgetConfig .form-group').addClass('hidden').each(function (index, item) {
                    var type = $(item).data('type');
                    if ($.inArray(type, Controller.baseForm) !== -1) {
                        $(item).removeClass('hidden');
                        if ($.inArray(data.type, FormBuilder.immutableSelectpageTypes) !== -1) {
                            $('input[name="row[name]"]', $(item)).attr('disabled', 'disabled');
                        } else {
                            $('input[name="row[name]"]', $(item)).removeAttr('disabled', 'disabled');
                        }
                    }
                    if (Controller.extraForm[data.type] !== undefined && $.inArray(type, Controller.extraForm[data.type]) !== -1) {
                        $(item).removeClass('hidden');
                    }
                });
                if ($.inArray(data.type, Controller.hideRestBtn) !== -1) {
                    $('button[type="reset"]').addClass('hidden');
                } else {
                    $('button[type="reset"]').removeClass('hidden');
                }
                if ($.inArray(data.type, Controller.suffixNameForm) !== -1) {
                    $('input[name="row[name]"]', '#widgetConfig').closest('div').addClass('input-group');
                    $('input[name="row[name]"]', '#widgetConfig').closest('div').find('.name-suffix').removeClass('hidden');
                } else {
                    $('input[name="row[name]"]', '#widgetConfig').closest('div').removeClass('input-group');
                    $('input[name="row[name]"]', '#widgetConfig').closest('div').find('.name-suffix').addClass('hidden');
                }
            },
            fillForm: function (data) {
                var type = data.type;
                $('input[name="row[name]"]').val(data.name);
                $('input[name="row[title]"]').val(data.title);
                $('input[name="row[defaultValue]"]').val(data.defaultValue);
                if ($.inArray(type, FormBuilder.decimalTypes) !== -1) {
                    $('input[name="row[decimal]"]').val(data.decimal);
                }
                if ($.inArray(type, FormBuilder.optionsTypes) !== -1) {
                    $('textarea[name="row[options]"]').val(JSON.stringify(data.options)).trigger("fa.event.refreshfieldlist");
                }
                if ($.inArray(type, FormBuilder.datasourceTypes) !== -1) {
                    $('input[name="row[datasource]"]').val(data.datasource);
                }
                if ($.inArray(type, FormBuilder.multipleTypes) !== -1) {
                    $('#multiple-' + data.multiple).prop('checked', 'checked');
                }
                if ($.inArray(type, Controller.suffixNameForm) !== -1) {
                    var multiple = data.multiple == undefined ? 1 : data.multiple;
                    var suffix = Controller.suffix[type][multiple];
                    $('span.name-suffix', '.input-group').html(suffix);
                }
            },
            saveData: function () {
                FormBuilder.setData(FormBuilder.currentWidgetId, Controller.addApi.getWidgetFormData());
            },
            getWidgetFormData: function () {
                var widgetId = FormBuilder.currentWidgetId;
                var widgetData = FormBuilder.getData(widgetId);
                var visibleFields = $.merge([], Controller.baseForm);
                if (Controller.extraForm[widgetData.type] !== undefined) {
                    $.merge(visibleFields, Controller.extraForm[widgetData.type]);
                }
                var formData = $('#widgetConfig-form').serializeArray();
                var data = {};
                for (var i = 0; i < visibleFields.length; i++) {
                    for (var j = 0; j < formData.length; j++) {
                        if (formData[j].name === 'row[' + visibleFields[i] + ']') {
                            if (formData[j].name === 'row[options]') {
                                data[visibleFields[i]] = JSON.parse(formData[j].value);
                            } else {
                                data[visibleFields[i]] = formData[j].value;
                            }
                            break;
                        }
                    }
                }
                return data;
            },
            buildOptions: function (widget, options) {
                var optionContainer = null;
                var optionHtml = '';
                var widgetId = widget.data('id');
                var widgetType = widget.data('type');
                if (widgetType === 'radio' || widgetType === 'checkbox') {
                    optionContainer = $('div.' + widgetType + '', $(widget));
                    var randId = FormBuilder.getRandId(8);
                    options.map(function (item) {
                        optionHtml += '<label for="' + randId + '"><input id="' + randId + '" checked="checked" name="row[' + widgetId + ']" type="' + widgetType + '" value="' + item.key + '"> ' + item.value + '</label>';
                    });
                    optionContainer.html(optionHtml);
                }

                if (widgetType === 'selectpicker') {
                    optionContainer = $('select.' + widgetType + '', $(widget));
                    options.map(function (item) {
                        optionHtml += '<option value="' + item.key + '">' + item.value + '</option>';
                    });
                    optionContainer.html(optionHtml);
                    optionContainer.selectpicker('refresh');
                }

            },
            refreshFieldlist: function (container) {
                var data = {};
                var name = container.data("name");
                var textarea = $("textarea[name='" + name + "']");
                var template = container.data("template");
                $.each($("input,select,textarea", container).serializeArray(), function (i, j) {
                    var reg = /\[(\w+)\]\[(\w+)\]$/g;
                    var match = reg.exec(j.name);
                    if (!match)
                        return true;
                    match[1] = "x" + parseInt(match[1]);
                    if (typeof data[match[1]] == 'undefined') {
                        data[match[1]] = {};
                    }
                    data[match[1]][match[2]] = j.value;
                });
                var result = template ? [] : {};
                $.each(data, function (i, j) {
                    if (j) {
                        if (!template) {
                            if (j.key != '') {
                                result[j.key] = j.value;
                            }
                        } else {
                            result.push(j);
                        }
                    }
                });
                textarea.val(JSON.stringify(result));
            },
            buildControlerStr: function (table) {
                var controller = '';
                table = table.replace(Config.prefix, '').replaceAll(' ', '');
                var strArray = table.split('_');
                strArray.forEach(function (item) {
                    if (item.length !== 0) {
                        controller += item.replace(item[0], item[0].toUpperCase());
                    }
                });
                return ('fastflow/bill/' + controller);
            },
            getFields: function () {
                var sort = FormBuilder.formData.sort;
                var fields = [];
                sort.forEach(function (item) {
                    let widgetData = FormBuilder.getData(item);
                    let suffix = '';
                    if ($.inArray(widgetData.type, Controller.suffixNameForm) !== -1) {
                        var multiple = widgetData.multiple == undefined ? 1 : widgetData.multiple;
                        suffix = Controller.suffix[widgetData.type][multiple];
                    }
                    fields.push({field: widgetData.name + suffix, comment: widgetData.title});
                });
                return fields;
            },
            updateFieldsSelect: function () {
                var fields = Controller.addApi.getFields();
                var select = $('select[name="fields[]"]', '#billConfig');
                var value = select.val();
                Controller.api.buildoptions(select, fields, 'fields', value);
            },
            clearRelation: function () {
                $('tr[fieldlist-item="true"]', '.relation-fieldlist').remove();
            },
            updateRelation: function () {
                var tablefields = Controller.addApi.getFields();
                if (tablefields.length === 0){
                    Controller.addApi.clearRelation();
                    return;
                }
                tablefields.push({field: 'initiator_id', comment: '发起人ID'});
                tablefields.push({field: 'id', comment: 'ID'});
                $('tr[fieldlist-item="true"]', '.relation-fieldlist').each(function (index, item) {
                    var relationMode = $('select.relationmode',item).val();
                    if(relationMode === 'belongsto'){
                        Controller.api.buildoptions($('select.relationforeignkey',item), tablefields, type = 'fields');
                    }
                    else if(relationMode === 'hasone'){
                        Controller.api.buildoptions($('select.relationprimarykey',item), tablefields, type = 'fields');
                    }
                });
            }
        },
        addEvents: {
            createBill: function () {
                $('.btn-createbill').click(function () {
                    var relationFields = [];
                    $('select.relationfields', '#billConfig-form').each(function (index, item) {
                        relationFields.push($(item).val());
                    });
                    Fast.api.ajax({
                        url: "fastflow/flow/bill/add",
                        data: {
                            billName: $('input[name="billName"]').val(),
                            billTable: $('input[name="billTable"]').val(),
                            createtime: $('input[name="row[createtime]"]').prop('checked'),
                            updatetime: $('input[name="row[updatetime]"]').prop('checked'),
                            formData: FormBuilder.formData,
                            configData: $('#billConfig-form').serializeArray(),
                            relationFields: relationFields
                        },
                    }, function (let, data) {
                        if (data['code'] == 1) {
                            parent.Toastr.success(data['msg']);
                            let index = parent.Layer.getFrameIndex(window.name);
                            parent.Layer.close(index);
                            top.window.$(".sidebar-menu").trigger("refresh");
                        } else if (data['code'] == 0) {
                            Toastr.error(data['msg']);
                        }
                    });
                });
            },
            clearClick: function () {
                $('.customform-clear').click(function () {
                    Layer.confirm(
                        __('确定清空吗?'),
                        {
                            icon: 3,
                            title: __('Warning'),
                            shadeClose: true,
                            btn: [__('OK'), __('Cancel')]
                        },
                        function (index) {
                            $('#customform').html('');
                            FormBuilder.clearData();
                            $('button[type="reset"]').trigger('click');
                            Controller.addApi.updateFieldsSelect();
                            Controller.addApi.clearRelation();
                            Layer.close(index);
                        }
                    );
                });
            },
            widgetRemove: function () {
                $('#customform').on('widget-remove', function (e, widget) {
                    if ($(widget).data('id') === FormBuilder.currentWidgetId || FormBuilder.formData.widget.length === 0) {
                        $('button[type="reset"]').trigger('click');
                    }
                    Controller.addApi.updateFieldsSelect();
                    Controller.addApi.updateRelation();
                });
            },
            widgetClick: function () {
                $('#customform').on('widget-click', function (e, data) {
                    Controller.addApi.initForm(data);
                });
            },
            sortableUpdate: function () {
                //更新单据配置显示字段下拉框选项
                $('#customform').on('widget-clone', function (e) {
                    Controller.addApi.updateFieldsSelect();
                    Controller.addApi.updateRelation();
                });
                $('#customform').on('sortable-update', function (e) {
                    Controller.addApi.updateFieldsSelect();
                    Controller.addApi.updateRelation();
                });
            },
            inputChange: function () {
                $('input[name="billTable"]').on('input propertychange', function (event) {
                    var controller = Controller.addApi.buildControlerStr($(this).val());
                    $('input[name=controller]').val(controller);
                });
                $('input', '#widgetConfig').on('input propertychange', function (event) {
                    if (FormBuilder.currentWidgetId === null) {
                        return false;
                    }
                    Controller.addApi.saveData();
                });
                $('input', 'div[data-type="multiple"]').on('input propertychange', function (event) {
                    if (FormBuilder.currentWidgetId === null) {
                        return false;
                    }
                    var currentDiv = $('div[data-id="' + FormBuilder.currentWidgetId + '"]');
                    currentDiv.trigger('click');
                    Controller.addApi.updateRelation();
                });
                $('input[name="row[name]"]', '#widgetConfig').on('input propertychange', function (event) {
                    var that = this;
                    if (FormBuilder.currentWidgetId === null) {
                        return false;
                    }
                    var currentWidget = $('div[data-id="' + FormBuilder.currentWidgetId + '"]');
                    var widgetType = currentWidget.data('type');
                    if ($.inArray(widgetType, FormBuilder.datasourceTypes) !== -1) {
                        var replaceSource = $(that).val().replaceAll('_', '/');
                        $('input[name="row[datasource]"]').val(replaceSource + '/index');
                    }
                    Controller.addApi.saveData();
                });
                $('input[name="row[title]"]', '#widgetConfig').on('input propertychange', function (event) {
                    if (FormBuilder.currentWidgetId === null) {
                        return false;
                    }
                    var currentWidget = $('div[data-id="' + FormBuilder.currentWidgetId + '"]');
                    $('.control-label', $(currentWidget)).html($(this).val());
                });

                $('.fieldlist', '#widgetConfig').on("fa.event.appendfieldlist", function (event, row) {
                    if (FormBuilder.currentWidgetId === null) {
                        return false;
                    }
                    $('input', $(row)).on('input propertychange', function (event) {
                        $('.fieldlist input:first-child').trigger('change');
						// 4.4.4---
                        var container = $(this).closest(".fieldlist");
                        Controller.addApi.refreshFieldlist(container);
						// ---4.4.4 
                        var currentWidget = $('div[data-id="' + FormBuilder.currentWidgetId + '"]');
                        var options = JSON.parse($('textarea[name="row[options]"]').val());
                        Controller.addApi.buildOptions(currentWidget, options);
                        Controller.addApi.saveData();
                    });
                    $('.btn-remove', $(row)).click(function () {
                        var container = $(this).closest(".fieldlist");
                        var tagName = container.data("tag") || (container.is("table") ? "tr" : "dd");
                        $(this).closest(tagName).remove();
                        Controller.addApi.refreshFieldlist(container);
                        var currentWidget = $('div[data-id="' + FormBuilder.currentWidgetId + '"]');
                        var options = JSON.parse($('textarea[name="row[options]"]').val());
                        Controller.addApi.buildOptions(currentWidget, options);
                        Controller.addApi.saveData();
                        return false;
                    });
                });
            },
            selectIcon: function () {
                var iconlist = [];
                var iconfunc = function () {
                    Layer.open({
                        type: 1,
                        title: '图标',
                        area: ['60%', '60%'],
                        content: Template('chooseicontpl', {iconlist: iconlist})
                    });
                };

                $(document).on('click', ".btn-search-icon", function () {
                    if (iconlist.length == 0) {
                        $.get(Config.site.cdnurl + "/assets/libs/font-awesome/less/variables.less", function (ret) {
                            var exp = /fa-var-(.*):/ig;
                            var result;
                            while ((result = exp.exec(ret)) != null) {
                                iconlist.push(result[1]);
                            }
                            iconfunc();
                        });
                    } else {
                        iconfunc();
                    }
                });
                $(document).on('click', '#chooseicon ul li', function () {
                    $("input[name='icon']").val('fa-' + $(this).data("font"));
                    Layer.closeAll();
                });
                $(document).on('keyup', 'input.js-icon-search', function () {
                    $("#chooseicon ul li").show();
                    if ($(this).val() != '') {
                        $("#chooseicon ul li:not([data-font*='" + $(this).val() + "'])").hide();
                    }
                });
            },
            billConfigTabClick: function () {
                $('#billConfigBtn').on('click', function () {

                    Controller.addApi.updateFieldsSelect();
                });
            },
            tableRelationChange: function () {
                $(document).on('click', "a.btn-newrelation", function () {
                    var tables = [];
                    Fast.api.ajax({
                        async: false,
                        url: "fastflow/flow/bill/getTablesAjax",
                    }, function (data, ret) {
                        data.forEach(function (table) {
                            tables.push({'value': table.name, 'name': table.name + '(' + table.comment + ')'});
                        });
                        return false;
                    });

                    var that = this;
                    $('select', $(that).closest('tr').prev()).selectpicker();
                    var exists = [];
                    $("select.relationtable").each(function () {
                        exists.push($(this).val());
                    });
                    relationtable = [];
                    tables.forEach(function (item) {
                        if ($.inArray(item['value'], exists) < 0) {
                            relationtable.push(item);
                        }
                    });

                    Controller.api.buildoptions($("select.relationtable", $(that).closest('tr').prev()), relationtable, 'table');
                });
                $(document).on('change', "select.relationmode", function () {
                    var tablefields = Controller.addApi.getFields();
                    tablefields.push({field: 'initiator_id', comment: '发起人ID'});
                    tablefields.push({field: 'id', comment: 'ID'});
                    var relationtable = $("select.relationtable", $(this).closest("tr")).val();
                    var that = this;
                    Fast.api.ajax({
                        url: "fastflow/flow/bill/getFieldsWithComment",
                        data: {table: relationtable},
                    }, function (data, ret) {
                        Controller.api.buildoptions($(that).closest("tr").find("select.relationprimarykey"), $(that).val() == 'belongsto' ? data : tablefields, type = 'fields');
                        Controller.api.buildoptions($(that).closest("tr").find("select.relationforeignkey"), $(that).val() == 'hasone' ? data : tablefields, type = 'fields');
                        return false;
                    });
                });
                $(document).on('change', "select.relationtable", function () {
                    var that = this;
                    Fast.api.ajax({
                        url: "fastflow/flow/bill/getFieldsWithComment",
                        data: {table: $(that).val()},
                    }, function (data, ret) {
                        Controller.api.buildoptions($(that).closest("tr").find("select.relationmode"), ["belongsto", "hasone"], 'item');
                        Controller.api.buildoptions($(that).closest("tr").find("select.relationfields"), data, type = 'fields');
                        Controller.addApi.updateRelation();
                        return false;
                    });
                });
            },
            collapseClick: function () {
                $('legend','#widget').click(function (e) {
                    var legend = $(this).closest('legend');
                    var dataWidget = legend.data('widget');
                    var dataCollapse = legend.data('collapse');
                    var widgets = $('div.' + dataWidget,'#widget');
                    var collapsIcon = $('.collapse-icon',legend);
                    dataCollapse == true ? (
                            widgets.removeClass('hidden'),
                            legend.data('collapse',false),
                            collapsIcon.removeClass('fa-plus').addClass('fa-minus')
                        ) : (
                            widgets.addClass('hidden'),
                            legend.data('collapse',true),
                            collapsIcon.removeClass('fa-minus').addClass('fa-plus')
                    );

                });
            }
        },
        fromApi: {
            bindevents: function () {
                Controller.fromEvents.tableRelationChange();
                Controller.fromEvents.selectIcon();
            },
        },
        fromEvents: {
            tableRelationChange: function () {
                var tables = [];
                $("select[name='table'] option").each(function () {
                    tables.push({'value': $(this).val(), 'name': $(this).html()});
                });
                var tablefields = [];
                $("select[name='table']").on('change', function () {
                    var that = this;
                    Fast.api.ajax({
                        url: "fastflow/flow/bill/getFieldsWithComment",
                        data: {table: $(that).val()},
                    }, function (data, ret) {
                        tablefields = data;
                        Controller.api.buildoptions($("#fields"), data, 'fields');
                        return false;
                    });
                    var controller = '';
                    $(that).val().replace(/_([a-zA-Z])+/g, function (arg) {
                        arg = arg.replace('_', '');
                        controller += arg.replace(arg[0], arg[0].toUpperCase());
                    })
                    $('input[name=controller]').val('fastflow/bill/' + controller);
                    return false;
                });
                $(document).on('click', "a.btn-newrelation", function () {
                    var that = this;
                    $('select', $(that).closest('tr').prev()).selectpicker();
                    var exists = [];
                    exists.push($("select[name='table']").val());
                    $("select.relationtable").each(function () {
                        exists.push($(this).val());
                    });
                    relationtable = [];
                    tables.forEach(function (item) {
                        if ($.inArray(item['value'], exists) < 0) {
                            relationtable.push(item);
                        }
                    });
                    Controller.api.buildoptions($("select.relationtable", $(that).closest('tr').prev()), relationtable, 'table');
                });
                $(document).on('change', "select.relationmode", function () {
                    var relationtable = $("select.relationtable", $(this).closest("tr")).val();
                    var that = this;
                    Fast.api.ajax({
                        url: "fastflow/flow/bill/getFieldsWithComment",
                        data: {table: relationtable},
                    }, function (data, ret) {
                        Controller.api.buildoptions($(that).closest("tr").find("select.relationprimarykey"), $(that).val() == 'belongsto' ? data : tablefields, type = 'fields');
                        Controller.api.buildoptions($(that).closest("tr").find("select.relationforeignkey"), $(that).val() == 'hasone' ? data : tablefields, type = 'fields');
                        return false;
                    });
                });
                $(document).on('change', "select.relationtable", function () {
                    var that = this;
                    Fast.api.ajax({
                        url: "fastflow/flow/bill/getFieldsWithComment",
                        data: {table: $(that).val()},
                    }, function (data, ret) {
                        Controller.api.buildoptions($(that).closest("tr").find("select.relationmode"), ["belongsto", "hasone"], 'item');
                        Controller.api.buildoptions($(that).closest("tr").find("select.relationfields"), data, type = 'fields');
                        return false;
                    });
                });
            },
            selectIcon: function () {
                var iconlist = [];
                var iconfunc = function () {
                    Layer.open({
                        type: 1,
                        title: '图标',
                        area: ['99%', '98%'],
                        content: Template('chooseicontpl', {iconlist: iconlist})
                    });
                };

                $(document).on('click', ".btn-search-icon", function () {
                    if (iconlist.length == 0) {
                        $.get(Config.site.cdnurl + "/assets/libs/font-awesome/less/variables.less", function (ret) {
                            var exp = /fa-var-(.*):/ig;
                            var result;
                            while ((result = exp.exec(ret)) != null) {
                                iconlist.push(result[1]);
                            }
                            iconfunc();
                        });
                    } else {
                        iconfunc();
                    }
                });
                $(document).on('click', '#chooseicon ul li', function () {
                    $("input[name='icon']").val('fa-' + $(this).data("font"));
                    Layer.closeAll();
                });
                $(document).on('keyup', 'input.js-icon-search', function () {
                    $("#chooseicon ul li").show();
                    if ($(this).val() != '') {
                        $("#chooseicon ul li:not([data-font*='" + $(this).val() + "'])").hide();
                    }
                });
            }
        },
        api: {
            buildoptions: function (select, data, type, value = null) {
                var html = '';
                data.forEach(function (e) {
                    if (type == 'fields') {
                        let selected = $.inArray(e['field'].toString(), value) != -1 ? 'selected' : '';
                        html += "<option value='" + e['field'] + "' " + selected + ">" + e['field'] + '(' + e['comment'] + ')' + "</option>";
                    } else if (type == 'table') {
                        let selected = $.inArray(e['value'].toString(), value) != -1 ? 'selected' : '';
                        html += "<option value='" + e['value'] + "' " + selected + ">" + e['name'] + "</option>";
                    } else if (type == 'item') {
                        let selected = $.inArray(e.toString(), value) != -1 ? 'selected' : '';
                        html += "<option value='" + e + "' " + selected + ">" + e + "</option>";
                    }
                });
                $(select).html(html);
                select.trigger("change");
                if (select.data("selectpicker")) {
                    select.selectpicker('refresh');
                }
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function (data) {
                    Fast.api.refreshmenu();
                });
            },
            formatter: {
                operate: function (value, row, index) {
                    return '<a href="fastflow/flow/bill/del?ids=' + row['id'] + '" class="btn btn-xs btn-danger btn-delone" data-toggle="tooltip" title="删除单据" data-table-id="table" data-field-index="12" data-row-index="0" data-button-index="2" data-original-title="删除单据"><i class="fa fa-trash"> 删除单据</i></a>';
                },
                billauth: function (value, row, index) {
                    return '<a href="fastflow/flow/bill/auth?bill=' + row['bill_table'] + '" class="btn btn-xs btn-warning btn-dialog"  data-toggle="tooltip" title="单据权限配置" data-table-id="table"  data-original-title="单据权限配置" style="font-size: 90%"><i class="fa fa-lock"></i> 权限配置</a>';
                },
            },
            events: {
                operate: {
                    'click .btn-delone': function (e, value, row, index) {
                        e.stopPropagation();
                        e.preventDefault();
                        var that = this;
                        var offsettop = $(that).offset().top - $(window).scrollTop();
                        var offsetleft = $(that).offset().left - $(window).scrollLeft() - 260;
                        if (offsettop + 154 > $(window).height()) {
                            offsettop = offsettop - 154;
                        }
                        if ($(window).width() < 480) {
                            offsettop = offsetleft = undefined;
                        }
                        var table = $(that).closest('table');
                        Layer.confirm(
                            __('删除单据会同时删除对应的控制器、模型、JS等文件，确认删除该单据吗?'),
                            {
                                icon: 3,
                                title: __('Warning'),
                                offset: [offsettop, offsetleft],
                                shadeClose: true,
                                btn: [__('OK'), __('Cancel')]
                            },
                            function (index) {
                                var options = table.bootstrapTable('getOptions');
                                Fast.api.ajax({
                                    url: $(that).attr('href'),
                                    data: {},
                                }, function (data, ret) {
                                    Layer.alert(ret.msg);
                                    table.bootstrapTable('refresh');
                                    top.window.$(".sidebar-menu").trigger("refresh");
                                    return false;
                                });
                                Layer.close(index);
                            }
                        );
                    }
                }
            },
        }
    };
    return Controller;
});